layui.use(["jquery","layer","form",'upload','laydate',"element"],function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var laydate=layui.laydate;
    var upload = layui.upload;
    var element = layui.element;

    var createDate = "";
    //刷新
    refresh = function refresh(){
        location.reload();
    }
    //返回按钮
    $('#goBack').click(function () {
        window.location.href="/user/userManage/userList/user-list.html";
    });

    //自定义表单验证规则
    form.verify({
        title: function(value){
            if(value.length < 5){
                return '标题至少得5个字符啊';
            }
        }, fname: function(value){
            if(value.length < 4){
                return '请输入至少4位的用户名';
            }
        }, contact: function(value){
            if(value.length < 4){
                return '内容请输入至少4个字符';
            }
        }
        ,phone: [/^1[3|4|5|7|8]\d{9}$/, '手机必须11位，只能是数字！']
        ,email: [/^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/, '邮箱格式不对']
        ,integration: [/^100$|^[123456789][0-9]$|^[0-9]$/,'请输入数字0~100']
    });


    //入学时间
    laydate.render({
        elem: '#entranceDate',
        type: 'datetime',
        trigger: 'click'
    })
    //开学时间
    laydate.render({
        elem: '#graduationDate',
        type: 'datetime',
        trigger: 'click'
    })
    //出身日期
    laydate.render({
        elem: '#birthDate',
        type: 'datetime',
        trigger: 'click'
    })

    //是否毕业
    var type=3;
    form.on("radio(type)",function (data) {
        if (data.value == "已毕业"){
            type = 3;
        }else {
            type = 2;
        }
    });
    //性别
    var sex = 1;
    form.on("radio(sex)",function (data) {
        if (data.value == "男"){
            sex = 1;
        }else {
            sex = 2;
        }
    });

    //上传图片
    var arr = [];
    upload.render({
        elem: "#upLoad",
        url: "/Upload/uploadFiles",
        method: "post",
        field: 'file',
        accept: 'file',//上传文件类型
        auto: false,//关闭自动上传
        bindAction: "#queding",
        multiple: true,
        before: function (obj) {
            layer.msg('图片上传中...', {
                icon: 16,
                shade: 0.01,
                time: 0
            })
        },
        choose: function (obj) {//走缓存
            //将每次选择的文件追加到文件队列
            var files = obj.pushFile();
            //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
            obj.preview(function (index, file, result) {
                if (file.size > 0 && $('#imgurls').find('img').length === 0) {
                    $('#imgurls').empty();
                }
                // 添加图片 ImgPreview-预览的dom元素的id
                $('#imgurls').append('<div style="float: left;" class="file-iteme" id="container' + index + '"><div class="handle"><i id="upload_img_' + index + '" class="layui-icon" style="color: white ;margin-right: 40%">&#xe640;</i></div>' +
                    '<img id="showImg' + index + '" style="cursor:pointer;"src="' + result + '" alt="' + file.name + '"></div>');
                //删除某图片
                $("#upload_img_" + index).bind('click', function () {
                    delete files[index];
                    $("#container" + index).remove();
                });
            });
        },
        done: function (res) {
            //上传完毕
            arr.push(res.data);
            element.progress('imgProgress', '100%');
            layer.msg("上传成功");
        },
        /*allDone: function(){
            $("#submitUser").click();
        }*/
    });

    $(document).on("mouseenter mouseleave", ".file-iteme", function (event) {
        if (event.type === "mouseenter") {
            //鼠标悬浮
            // $(this).children(".info").fadeIn("fast");
            $(this).children(".handle").fadeIn("fast");
        } else if (event.type === "mouseleave") {
            //鼠标离开
            // $(this).children(".info").hide();
            $(this).children(".handle").hide();
        }
    });


    form.on('submit(demo1)', function(data){
        $("#submitUser").click();
        return true;
    });

    //点击提交按钮
    $("#submitUser").click(function () {
        var userCode = $("#userCode").val();//学号
        var user = JSON.parse(localStorage.getItem('user'));
        var createId = user.data.userId;
        //给头像路径赋值
        for (var i = 0; i < arr.length; i++) {
            if (i == 0) {
                $("#url").val(arr[i]);
            }
        }
        var url = $("#url").val();
        getTime();
        if(url == null | url ==''){//会走到里面单不会跳窗
            layer.msg("请上传图片");
            return;
        }else if(userCode != null){
            $.ajax({
                url:"/user/getBeforeUser",
                data:{},
                type:'post',
                dataType:"json",
                success:function (data) {
                    var arr = [];
                    for (var i = 0; i < data.data.length ; i++) {
                        arr.push(data.data[i].userCode);
                    }
                    var num = 0;
                    for (var i = 0; i <= arr.length ; i++) {
                        if (arr[i] == userCode) {
                            layer.msg("学号已存在");
                            return;
                        }
                        if (arr[i] != userCode&&arr.length!=0) {
                            num++;
                        }
                        if (num == arr.length) {
                            var param = {
                                "photoImg":$("#url").val(),
                                'phone':$("#phone").val(),
                                "account":$("#account").val(),
                                "nickname":$("#nickname").val(),
                                'userCode':$("#userCode").val(),
                                'avatarUrl':$("#url").val(),
                                'studyDate':$("#studyDate").val(),
                                "status":2,
                                "freestyle":$("#freestyle").val(),
                                'idCard':$("#idCard").val(),
                                'sex':sex,
                                'birthDate':$("#birthDate").val(),//出身日期
                                "email":$("#email").val(),
                                'remarks':$("#remarks").val(),
                                'intention':$("#intention").val(),
                                'consumption':$("#consumption").val(),
                                'createDate': createDate,
                                'fullName':$("#fullName").val()
                            }
                            console.log(param);
                            $.ajax({
                                url: "/user/addBeforeUser",
                                data: param,
                                type: 'post',
                                dataType: 'json',
                                success: function (data) {
                                    $.ajax({
                                        url:"/user/getUserId",
                                        data:{'userCode' : userCode},
                                        type:'post',
                                        dataType:'json',
                                        success:function (data) {
                                            var userId = data.data[0].userId
                                            var params = {
                                                'userId':userId,
                                                'profession':$("#profession").val(),
                                                'type':type,
                                                'studyContent':$("#studyContent").val(),
                                                'integration':$("#integration").val(),
                                                'entranceDate':$("#entranceDate").val(),
                                                'graduationDate':$("#graduationDate").val(),
                                                'createId':createId,
                                                'createDate': createDate
                                            }
                                            console.log(params);
                                            $.ajax({
                                                url:"/user/addUserDevelopment",
                                                data:params,
                                                type:'post',
                                                dataType:'json',
                                                success:function(){
                                                    layer.msg("添加成功");
                                                    window.location.href="user-list.html";
                                                }
                                            })
                                        }
                                    })

                                }
                            })

                        }
                    }
                }

            })
        }
    })

    function getTime(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        createDate = dateStr;
    }
    function zeroFilling(data){
        if(data<10){
            data="0"+data;
        }
        return data;
    }
})